/**
 * VUEshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.vueshop.com.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: 沈小白 2020-07-22 $
 */
import store from '@/store'
module.exports={
	//检测是否登录
	islogin:function(){
		/*获取上页面的路径*/
		let pageArr=getCurrentPages();
		let pageData;
		if(pageArr.length>1){
			//#ifdef H5
			pageData=getCurrentPages()[1].__page__;
			// #endif
			//#ifdef MP
			pageData=getCurrentPages()[1].$page;
			// #endif
			// #ifdef APP-PLUS
			pageData=getCurrentPages()[1].route
			// #endif
		}else{
			//#ifdef H5
			pageData=getCurrentPages()[0].__page__;
			// #endif
			//#ifdef MP
			pageData=getCurrentPages()[0].$page;
			// #endif
			// #ifdef APP-PLUS
			pageData=getCurrentPages()[0].route
			// console.log(pageData)
			// #endif
		}
		store.dispatch('setPrePage',pageData)
		if(!store.state.hasLogin){
			//除了h5都跳转
			//#ifdef MP
			uni.redirectTo({
				url:"/pages/user/get_user_info/get_user_info"
			})
			//#endif
			//h5跳转
			//#ifdef H5
			uni.redirectTo({
				url:"/pages/user/login/login"
			})
			//#endif
			//#ifdef APP-PLUS
			uni.navigateTo({
				url:"/pages/user/login/login"
			})
			//#endif
		}
	},
	//弹窗
	/*icon传参数 showToast的参数
	time: number类型
	*/
	toast:function(icon,title,time,isBlack){
		uni.showToast({
			icon:icon,
		    title: title,
		    duration: time,
			mask: true,
		});
		setTimeout(function () {
		   if(isBlack){
		   	uni.navigateBack({
		   		delta:1
		   	})
		   }
		}, time);
	},
	model:function(content,isBack){
		uni.showModal({
		    title:"",
		    content: content,
			showCancel:false,
		    success: function (res) {
		        if (res.confirm) {
		            // console.log('用户点击确定');
					if(isBack==true){
						uni.navigateBack({
							delta:1
						})
					}
		        } else if (res.cancel) {
		            // console.log('用户点击取消');
		        }
		    }
		});
	},
	//路径回退 num number类型  1
	jump:function(num){
		let pages=getCurrentPages()
		// #ifdef H5
		let router=pages[0].route;
		//#endif
		// #ifdef MP
		let router=pages[0].$page;
		//#endif
		// #ifdef APP-PLUS
		let router=pages[1].route;
		//#endif
		let prePage=store.state.prePage;
		this.isIndexRoute(prePage)

	},
	//判断是跳转缓存路径还是跳转到首页
	isIndexRoute(prePage) {
		/*先判断缓存路径==登录页路径?'个人中心':'缓存路径'*/
		let route = this.testRoute(prePage.fullPath);
		if(route=='/pages/user/login/login' || route == '/pages/user/get_user_info/get_user_info') {
			uni.switchTab({
				url: '/pages/user/user/user'
			});
		}else if(!route) {
			uni.switchTab({
				url: '/pages/user/user/user'
			});
		}else {
            let action = this.testJumpType(route).type
			uni[action]({ url:route})
        }
	},
	//跳转方法
	testJumpType(route) {
		// 判断跳转方法 是底部导航栏的就用switchTab方法
		let object = {
			route :route,
			type :""
		}
		let navroute = [
			'/pages/user/user/user',
			'/pages/cart/cart/cart',
			'/pages/classify/classify',
			'/pages/index/index',
            '/pages/publish/publish_list/publish_list'
		]
		const found = navroute.find(element => element == route);
		if(found != undefined) {
			object.type = 'switchTab'
		} else {
			object.type = 'redirectTo'
		}
		return object

	},
	// 检测路由
	testRoute(route) {
		if(route&&route.indexOf('/')!=0) {
			route = `/${route}`
		}
		return route
	},
	Obj2Str:function(obj) {
	    var str = '';
	    for (var i in obj) {
	        str += (str ? '&' : '') + i + '=' + obj[i]
	    }
	    return str;
	},
	/** 格式化时间 */
	format:function(timestamp, fmt) {
	    var date = new Date();
	    date.setTime(timestamp * 1000);
	    var o = {
	        "M+": date.getMonth() + 1, //月份
	        "d+": date.getDate(), //日
	        "h+": date.getHours(), //小时
	        "m+": date.getMinutes(), //分
	        "s+": date.getSeconds(), //秒
	        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
	        "S": date.getMilliseconds() //毫秒
	    };
	    if (typeof fmt == 'undefined') fmt = 'yyyy-MM-dd hh:mm:ss';
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	},
	//验证密码
	// 对应的验证规则是：密码中必须包含字母、数字、特称字符，至少6个字符，最多16个字符。
	VerifyPassword(password){
		var regex = new RegExp('^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$'); //符合格式的
		var num =new RegExp('^[0-9]{6,16}$') //验证数字
		if(num.test(password)==true){
			this.toast("none","密码不能全是数字",3000)
			return false
		}
		if(regex.test(password)==true){
			return regex.test(password)
		}else{
			this.toast("none","密码过于简单",3000)
			return false;
		}

	},
	remainTime(diffms) { //倒计时
		const daysms = 24 * 60 * 60 * 1000;
		const hoursms = 60 * 60 * 1000;
		const minutems = 60 * 1000;
		const secondms = 1000;
		var result = '';
		var hasfrontVal = false;
		var differDay = Math.floor(diffms / daysms);
		result = differDay ? differDay + '天' : '0天';
		hasfrontVal = differDay ? true : false;

		diffms -= differDay * daysms;
		var differHour = Math.floor(diffms / hoursms);
		result += differHour ? differHour + '时' : '0时';
		hasfrontVal = differHour ? true : false;

		diffms -= differHour * hoursms;
		var differMinute = Math.floor(diffms / minutems);
		result += differMinute ? differMinute + '分' : '0分';

		diffms -= differMinute * minutems;
		var differSecond = Math.floor(diffms / secondms);
		result += differSecond ? differSecond + '秒' : '0秒';

		return result;
	},
	/*设置sessionStorage值*/
	setSessionData(key,data) {
		// let storage = window.sessionStorage;
		// storage.setItem(key, JSON.stringify(data));
		uni.setStorageSync(key,data)
	},
	/*获取sessionStorage值*/
	getSessionData(key) {
		// let storage = window.sessionStorage;
		// let data;
		// data =  JSON.parse(storage.getItem(key)) || [];
		let data = uni.getStorageSync(key) || [];
		return data;
	},
	/*清除指定值  sessionStorage*/
	removeSessionItem(key) {
		// let storage = window.sessionStorage;
		// storage.removeItem(key);
		uni.removeStorageSync(key);
	},
	/*清除所有 sessionStorage*/
	clearSession() {
		// sessionStorage.clear();
		uni.clearStorageSync()
	},
	/*检测手机号*/
	testPhone(value) {
		/*
		国内手机号
		const zhreg= /^1[3456789]\d{9}$/
		*/

		/*
		美国手机号
		const usreg = /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/;
		*/
		const mobileReg =  /^((1[3456789]\d{9})|((\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}))$/
		return mobileReg.test(value);
	},

	removejscssfile(filename,filetype){
    var targetelement=(filetype=="js")? "script" :(filetype=="css")? "link" : "none"
    var targetattr=(filetype=="js")?"src" : (filetype=="css")? "href" :"none"
    var allsuspects=document.getElementsByTagName(targetelement)
    for (var i=allsuspects.length; i>=0;i--){
    if (allsuspects[i] &&allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
      allsuspects[i].parentNode.removeChild(allsuspects[i])
		}
	},

	removeElementById (id) {
		var idObject = document.getElementById(id);
		if (idObject != null)
				idObject.parentNode.removeChild(idObject);
	}


}
